package thread;

/**
 * 当多个线程同时操作同一临界值时，由于线程的切换实际是不确定性，导致的混乱
 * 导致线程的运行结果不确定
 * 并发安全问题
 *
 * 临界资源：操作该资源的过程同时只能被单线程进行
 */
public class SyncDemo1 {
    private static boolean success1;
    private static boolean success2;
    public static void main(String[] args) {
        //
        Band band = new Band();
        int num=0;
        while (true) {
            num++;
            //线程1
            Thread t1 = new Thread() {
                public void run() {
                    success1 = band.getMony(20000);
                }
            };
            //线程2
            Thread t2 = new Thread() {
                public void run() {
                    success2 = band.getMony(20000);
                }
            };

            t1.start();
            t2.start();
            //主线程等待
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (success1 && success2) {
                System.out.println("卡BUG成功,取4万块,"+num+"测试次数");
                break;//跳出循环
            } else {
                //System.out.println("卡BUG失败，被抓");
                success1=false;
                success2=false;
                band.saveAccount(20000);

            }
        }




    }
}
class Band{
    private int account=20000;
    //synchronized 同步
    public synchronized boolean getMony(int money){
        int account=getAccount();//获取账户余额
        if (account>=money){
            account-=money;
            //
            Thread.yield();
            saveAccount(account);
            return true;
        }
        return false;
    };
    public void saveAccount(int account){
        this.account=account;
    }
    public int getAccount(){
        return account;
    }
}